package com.xdq.serviceedu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xdq.serviceedu.entity.EduSubject;
import com.xdq.serviceedu.entity.EduTeacher;
import com.xdq.serviceedu.entity.excel.SubjectData;
import com.xdq.serviceedu.entity.subject.OneSubject;
import com.xdq.serviceedu.entity.subject.TwoSubject;
import com.xdq.serviceedu.listener.SubjectExcelListener;
import com.xdq.serviceedu.mapper.EduSubjectMapper;
import com.xdq.serviceedu.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-09-13
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(this)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);

        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);

        List<OneSubject> finalSubjcet = oneSubjectList
                .stream()
                .map( eduSubject -> {
                    List<TwoSubject> children = twoSubjectList
                            .stream()
                            .filter(eduSubject2 -> Objects.equals(eduSubject2.getParentId(), eduSubject.getId()))
                            .map(eduSubject3 -> new TwoSubject(eduSubject3.getId(), eduSubject3.getTitle()))
                            .collect(Collectors.toList());
                    return new OneSubject(eduSubject.getId(), eduSubject.getTitle(), children);
                }).collect(Collectors.toList());

        return finalSubjcet;
    }
}
